package db;

import java.sql.*;

public class DBConntection {
    public DBConfig config;


    public DBConntection(DBConfig config) {
        this.config = config;
    }

    public DBConntection() {
        this.config = null;
    }


//    static {
////        try {
////            // 1.加载驱动程序
////            Class.forName("com.mysql.jdbc.Driver");
////            // 2.获得数据库的连接
////        } catch (ClassNotFoundException e) {
////            e.printStackTrace();
////        }
////    }


    public Connection getConnection() {
        Connection connection = null;
        if (this.config != null) {
            try {
                connection = DriverManager.getConnection(this.config.url, this.config.username, this.config.password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("DBConfig is null!");
        }
        return connection;
    }

    public void closeJDBC(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            try {
                System.out.println("(rs) close conn:" + conn);
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                System.out.println("(stmt) close conn:" + conn);
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                System.out.println("(conn) close conn:" + conn);
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {

        DBConfig config = new DBConfig("jdbc:mysql://localhost:3360/itoffer?useUnicode=true&characterEncoding=utf8", "root", "docker");
        Connection conn1 = (new DBConntection(config)).getConnection();
        Connection conn2 = (new DBConntection(config)).getConnection();
        System.out.println(conn1.toString());
        System.out.println(conn2.toString());
    }

}
